package com.hoshiicloud.user.service.impl.organization;

import com.baomidou.mybatisplus.core.conditions.Wrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hoshiicloud.common.aop.Logable;
import com.hoshiicloud.common.exception.CommonError;
import com.hoshiicloud.common.exception.ServiceException;
import com.hoshiicloud.common.utils.UidGenerate4C;
import com.hoshiicloud.user.entity.company.ComDepartments;
import com.hoshiicloud.user.entity.company.Company;
import com.hoshiicloud.user.entity.organization.ComOrganization;
import com.hoshiicloud.user.feign.IdGeneratorService;
import com.hoshiicloud.user.mapper.organization.ComOrganizationMapper;
import com.hoshiicloud.user.service.company.IComDepartmentsService;
import com.hoshiicloud.user.service.company.ICompanyService;
import com.hoshiicloud.user.service.organization.ComOrganizationService;
import com.hoshiicloud.user.service.rbac.IMemberService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.List;

/**
 * <p>
 * 租户供应商 服务实现类
 * </p>
 *
 * @author campchen
 * @since 2019-04-28
 */
@Service
public class ComOrganizationServiceImpl extends ServiceImpl<ComOrganizationMapper, ComOrganization> implements ComOrganizationService {

    @Autowired
    private IdGeneratorService idGeneratorService;

    @Autowired
    private ICompanyService companyService;

    @Autowired
    private IComDepartmentsService comDepartmentsService;

    @Autowired
    private CommonService commonService;

    @Autowired
    private ComOrganizationMapper comOrganizationMapper;

    /**
     * @Author:campchen
     * @Description:
     * @Date:上午 10:45 2019/6/14
     * @Param:
     * @return:
     */
    @Override
    @Cacheable(cacheNames = "ComOrganization", key = "#root.targetClass.simpleName+':'+#root.methodName+':'+#key")
    @Logable(authName = "根据机构信息进行分页查询")
    public IPage<ComOrganization> getPage(IPage<ComOrganization> page, QueryWrapper<ComOrganization> queryWrapper, String key) {
        return baseMapper.selectPage(page, queryWrapper);
    }

    @Override
    @Cacheable(cacheNames = "ComOrganization", key = "#root.targetClass.simpleName+':'+#root.methodName+':'+#id")
    @Logable(authName = "根据id物理删除租户供应商信息")
    public boolean deleteById(Long id) {
        int row=baseMapper.deleteById(id);
        if (row<0){
            throw new ServiceException(CommonError.error("物理删除失败"));
        }
        return true;
    }


    /**
     * @param id
     * @return com.hoshiicloud.organization.entity.ComOrganization
     * @description: 根据id查询机构表
     */
    @Cacheable(cacheNames = "ComOrganization", key = "#root.targetClass.simpleName+':'+#root.methodName+':'+#id")
    @Logable(authName = "供应商信息-机构表 -查询机构表 ")
    @Override
    public ComOrganization getById(Long id) {
        return baseMapper.selectById(id);
    }


    @Cacheable(cacheNames = "ComOrganization", key = "#root.targetClass.simpleName+':'+#root.methodName+':'+#key")
    @Logable(authName = "供应商信息-机构表 -查询机构表 ")
    @Override
    public List<ComOrganization> getByIds(List<Long> ids, String key) {
        return baseMapper.selectBatchIds(ids);
    }

    @Cacheable(cacheNames = "ComOrganization", key = "#root.targetClass.simpleName+':'+#root.methodName+':'+#orgcode")
    @Logable(authName = "供应商信息-机构表 -查询机构表 ")
    @Override
    public ComOrganization getByOrgcode(String orgcode) {
        Wrapper<ComOrganization> wrapper = Wrappers.<ComOrganization>query().lambda().eq(ComOrganization::getOrgCode, orgcode);
        return baseMapper.selectOne(wrapper);
    }


    /**
     * @param entity
     * @return boolean
     * @description: 新增机构表
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    @CacheEvict(cacheNames = "ComOrganization", allEntries = true)
    @Logable(authName = "供应商信息-机构表-新增机构表")
    public String insert(ComOrganization entity) {
        String id = idGeneratorService.queryGeneratorId();
        StringBuffer errors = new StringBuffer("新增失败");
        if (StringUtils.isBlank(id)) {
            errors.append(",id生成有误");
        }
        Company company = companyService.getById(entity.getCompanyId());
        if (null == company) {
            errors.append(",公司信息有误");
        }
        ComDepartments comDepartments = comDepartmentsService.getById(entity.getDepartmentId());
        if (null == comDepartments) {
            errors.append(",公司部门信息有误");
        }

        //判断编码是否可用
        String orgcode = null;
        Boolean flag = true;
        int num = 1;
        //生成7位编码
        UidGenerate4C idWorker = new UidGenerate4C(num);
        while (flag) {
            num++;
            orgcode = "5" + "2" + String.valueOf(idWorker.getNextId()).substring(10, 17);
            ComOrganization comOrganizationOrgCode = getByOrgcode(orgcode);
            //当表中无此编码时，退出循环。
            if (comOrganizationOrgCode == null || "".equals(comOrganizationOrgCode)) {
                flag = false;
            }
            //此处为强制结束条件，可根据实际的条件来进行判断。
            if (num > 1000) {
                errors.append(",编码生成有误");
                flag = false;
            }
        }

        if (!"新增失败".equals(errors.toString())) {
            throw new ServiceException(CommonError.error(errors.toString()));
        }
        entity.setOrgCode(orgcode);
        entity.setId(Long.parseLong(id));
        entity.setCreatedTime(LocalDateTime.now());
        entity.setStatus(0);
        int row = baseMapper.insert(entity);
        if (row <= 0) {
            throw new ServiceException(CommonError.error("新增失败"));
        }
        return id;
    }

    /**
     * @param entity
     * @return boolean
     * @description: 修改机构表
     */
    @Transactional(rollbackFor = Exception.class)
    @CacheEvict(cacheNames = "ComOrganization", allEntries = true)
    @Logable(authName = "供应商信息-机构表管理-修改机构表")
    @Override
    public boolean updateById(ComOrganization entity) {
        /**如果供应商资料已修改需重新审核供应商资料*/
        if (entity.getStatus() == null || "".equals(entity.getStatus())) {
            entity.setStatus(0);
        }
        entity.setModifiedTime(LocalDateTime.now());
        int row = baseMapper.updateById(entity);
        if (row <= 0) {
            throw new ServiceException(CommonError.error("修改失败"));
        }
        return true;
    }

    /**
     * @Author:campchen
     * @Description: 0-未审批 1-已审批 2-已终止合作
     * @Date:上午 10:41 2019/5/24
     * @Param: id, sataus
     * @return: boolean
     */
    @Override
    public boolean updateById(Long id, Integer status) {
        commonService.approval(status);
        ComOrganization comOrganization = new ComOrganization();
        comOrganization.setId(id);
        comOrganization.setStatus(status);
        comOrganization.setModifiedTime(LocalDateTime.now());
        int row = baseMapper.updateById(comOrganization);
        if (row <= 0) {
            throw new ServiceException(CommonError.error("修改失败"));
        }
        return true;
    }


    @Override
    public List<ComOrganization> selectOrganizationByMemberId(Long memberId) {
        return comOrganizationMapper.selectOrganizationByMemberId(memberId);
    }

    @Override
    public List<ComOrganization> selectOrgByName(String name) {
        QueryWrapper<ComOrganization> queryWrapper=new QueryWrapper();
        queryWrapper.lambda().eq(name!=null,ComOrganization::getName,name);
        return baseMapper.selectList(queryWrapper);
    }
}
